/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.cashmate.struts;

import com.cashmate.hibernate.dao.AreaDAO;
import com.cashmate.hibernate.dao.BranchDAO;
import com.cashmate.hibernate.dao.DccrDAO;
import com.cashmate.hibernate.pojo.Areas;
import com.cashmate.hibernate.pojo.Branches;
import com.cashmate.hibernate.pojo.Dccr;
import com.cashmate.hibernate.pojo.Employees;
import com.cashmate.hibernate.pojo.Performance;
import com.cashmate.utilities.PerformanceObject;
import com.cashmate.utilities.Utils;
import com.opensymphony.xwork2.ActionSupport;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Actions;
import org.apache.struts2.convention.annotation.Result;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.ProjectionList;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.joda.time.DateTime;

/**
 *
 * @author dine
 */
@Result(name = "error", type = "redirect", location = "../error/messages.jsp")
public class Charts extends ActionSupport {

    private static final Logger logger = Logger.getLogger(Charts.class);
    private Map<String, Double> branchPerformanceMap, areaPerformanceMap;
    private final DccrDAO dccrdao = (DccrDAO) ServletActionContext.getServletContext().getAttribute("dccrDAO");
    private final BranchDAO branches = (BranchDAO) ServletActionContext.getServletContext().getAttribute("branchDAO");
    private final GridMonthperf gridMonthPerf = new GridMonthperf();
    private final Branches br = (Branches) ServletActionContext.getRequest().getSession().getAttribute("branch");
    private final AreaDAO areas = (AreaDAO) ServletActionContext.getServletContext().getAttribute("areaDAO");
    private String month, branchname;

    @Actions({
        @Action(value = "/charts", results = {
            @Result(location = "home.jsp", name = "success")
        })
    })
    @Override
    public String execute() throws Exception {
        try {
            List<Branches> branchList = branches.getAll();
            String bCode = "";
            DateTime maxDate = null;
            Object[] result;
            if (month == null) {
                DetachedCriteria criteria = DetachedCriteria.forClass(Dccr.class);
                criteria.add(Restrictions.eq("isactive", true));
                ProjectionList pl = Projections.projectionList();
                pl.add(Projections.property("dategenerated"));
                pl.add(Projections.property("branchcode"));
                pl.add(Projections.property("branchid"));
                criteria.setProjection(pl);
                criteria.addOrder(Order.desc("dategenerated"));
                criteria.addOrder(Order.asc("branchid"));
                result = (Object[]) dccrdao.findSingleProjectedCriteria(criteria);
                maxDate = Utils.stringArrToDateTime(result[0].toString().split("/"));
                //logger.debug(result[0].toString() + " " + result[1].toString());

                if (!br.getBranchcode().equals("HO")) {
                    bCode = br.getBranchcode();
                } else {
                    bCode = result[1].toString();
                }
            }else{
                result = month.split("-");
                maxDate = new DateTime().withYear(Integer.parseInt(result[1].toString())).withMonthOfYear(Integer.parseInt(result[0].toString())).withDayOfMonth(1);
                bCode = branches.get(Integer.parseInt(result[2].toString())).getBranchcode();
            }
            branchname = branches.getByBranchCode(bCode).getBranchname();
            //logger.debug("MAX DATE: " + maxDate.toString("MM/dd/yyyy"));
            //logger.debug(maxDate.getMonthOfYear() + " " + maxDate.getYear());
            for (Branches b : branchList) {
                if (b.isIsactive()) {
                    List<Performance> performanceList = dccrdao.monthlyPerformanceProcedure(maxDate.getMonthOfYear(), maxDate.getYear(), b.getBranchid(), null);
                    PerformanceObject po = gridMonthPerf.computeOverAll(performanceList);
                    //logger.debug("Branch: " + b.getBranchname() + " - " + ClassUtils.toString(po));
                    if (branchPerformanceMap == null && po != null) {
                        branchPerformanceMap = new HashMap<String, Double>();
                    }
                    if (!branchPerformanceMap.containsKey(b.getBranchname())) {
                        branchPerformanceMap.put(b.getBranchname(), po.getTotalperarea());
                    }
                    //logger.debug(b.getBranchid() + " " + br.getBranchid() + " "
                    //+ br.getBranchname() + " " + b.getBranchname());
                    if (b.getBranchcode().equals(bCode)) {
                        //logger.debug("YEA");
                        if (areaPerformanceMap == null) {
                            areaPerformanceMap = new HashMap<String, Double>();
                        }
                        //System.out.println(areaPerformanceMap.toString());
                        List<Areas> areaList = areas.getAreasPerBranch(b.getBranchid());
                        //logger.debug(areaList.size());
                        for (Areas a : areaList) {
                            List<Performance> perfList = dccrdao.monthlyPerformanceProcedure(maxDate.getMonthOfYear(), maxDate.getYear(), b.getBranchid(), a.getAreacode());
                            PerformanceObject po2 = gridMonthPerf.computeOverAll(perfList);
                            //logger.debug("Branch: " + b.getBranchname() + "Area: " + a.getAreacode() + " - " + ClassUtils.toString(po2));
                            if (!areaPerformanceMap.containsKey(a.getAreacode())) {
                                areaPerformanceMap.put(a.getAreacode(), po2.getTotalperarea());
                            }
                        }
                    }
                }
            }
        } catch (Exception ex) {
            Employees emps = (Employees) ServletActionContext.getRequest().getSession().getAttribute("employee");
            if (emps != null) {
                logger.fatal("(" + emps.getIdnumber() + "):" + ex.getLocalizedMessage(), ex);
            } else {
                logger.fatal(ex.getLocalizedMessage(), ex);
            }
            addActionError(ex.getLocalizedMessage());
            ex.printStackTrace();
            return ERROR;
        } finally {
            DccrDAO.close();
            BranchDAO.close();
        }
        return SUCCESS;
    }

    public Map<String, Double> getBranchPerformanceMap() {
        return branchPerformanceMap;
    }

    public Map<String, Double> getAreaPerformanceMap() {
        return areaPerformanceMap;
    }

    public void setMonth(String month) {
        this.month = month;
    }

    public String getBranchname() {
        return branchname;
    }
}
